package org.javacore.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Administrator on 2017/2/15.
 */
public class ReadWriteLockMap<K,V> {
    private Map<K,V> map = new HashMap<K, V>();

    private ReadWriteLock lock = new ReentrantReadWriteLock();


    public V get(K k) {
        V value = null;
        lock.readLock().lock();
        try {
            value = map.get(k);
        }finally {
            lock.readLock().unlock();
        }
        return value;
    }

    public void set(K k, V v) {
        lock.writeLock().lock();
        try {
            map.put(k,v);
        }finally {
            lock.writeLock().unlock();
        }
    }

    public V remove(K k) {
        V value = null;
        lock.writeLock().lock();
        try {
            value = map.remove(k);
        }finally {
            lock.writeLock().unlock();
        }
        return value;
    }

    public boolean containsKey(K k) {
        boolean flag = false;
        lock.readLock().lock();
        try {
            flag = map.containsKey(k);
        }finally {
            lock.readLock().unlock();
        }
        return flag;
    }
}
